package com.ycy.smartcourseselection.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycy.smartcourseselection.common.Constant;
import com.ycy.smartcourseselection.common.ResCodeEnum;
import com.ycy.smartcourseselection.common.ResData;
import com.ycy.smartcourseselection.dto.token.TokenInfoDTO;
import com.ycy.smartcourseselection.dto.token.UserInfo;
import com.ycy.smartcourseselection.entity.Student;
import com.ycy.smartcourseselection.entity.Teacher;
import com.ycy.smartcourseselection.exception.CustomException;
import com.ycy.smartcourseselection.service.StudentService;
import com.ycy.smartcourseselection.service.TeacherService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class TokenUtils {
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;

    private static TeacherService staticTeacherService;
    private static StudentService staticStudentService;

    @PostConstruct
    private void setStaticUserService() {
        staticTeacherService = teacherService;
        staticStudentService = studentService;
    }


    //生成token
    public static String getToken(UserInfo userInfo, String role) {
        String workOrStudentId;
        // String password;

        if ("TCH".equals(role)) {
            workOrStudentId = String.valueOf(userInfo.getTeacher().getWorkId());
            // password = userInfo.getTeacher().getPassword();
        } else if ("STU".equals(role)) {
            workOrStudentId = String.valueOf(userInfo.getStudent().getStudentId());
            // password = userInfo.getStudent().getPassword();
        } else {
            throw new CustomException(ResCodeEnum.SERVER_ERROR, "生成token时传递的role值错误");
        }

        return JWT.create().withAudience(workOrStudentId)  //将id作为 token的载荷
                // .withExpiresAt(DateUtil.offsetMinute(new Date(), 1))  //设置token有效期,这里设置为6小时
                .withExpiresAt(DateUtil.offsetHour(new Date(), 6))  //设置token有效期,这里设置为6小时
                .sign(Algorithm.HMAC256(Constant.MY_TOKEN_KEY));  //以自定义的密钥作为签名生成 token
    }

    //根据token查询用户信息
    public static ResData<UserInfo> getInfoByToken(TokenInfoDTO tokenInfoDTO) {
        String token = tokenInfoDTO.getToken();
        Integer role = tokenInfoDTO.getRole();  //0是学生，1是老师
        UserInfo userInfo = new UserInfo();


        // HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // String token = request.getHeader("token");

        if (StrUtil.isNotBlank(token)) {
            String workOrStudentId = JWT.decode(token).getAudience().get(0);

            if (role == 1) {
                QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("work_id", workOrStudentId);
                List<Teacher> list = staticTeacherService.list(queryWrapper);
                if (list.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "角色错误或该工号的教师不存在");
                if (list.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该工号的教师");

                Teacher teacher = new Teacher();
                BeanUtil.copyProperties(list.get(0), teacher);
                userInfo.setTeacher(teacher);

            } else if (role == 0) {
                QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("student_id", workOrStudentId);
                List<Student> list = staticStudentService.list(queryWrapper);
                if (list.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "角色错误或该学号的学生不存在");
                if (list.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该学号的学生");

                Student student = new Student();
                BeanUtil.copyProperties(list.get(0), student);
                userInfo.setStudent(student);
            } else {
                throw new CustomException(ResCodeEnum.SERVER_ERROR, "token中的参数role值错误");
            }

        }

        return ResData.success(userInfo);
    }
}
